#Region "Copyright (c) 2007 by Gerhard Kreuzer"
'/*--------------------------------------------------------------------------------------------------
' *  PostSharp, a post-compiler for the .NET Platform
' *  by Gael Fraiteur and community, http://www.postsharp.org
'*
' *  This sample is provided by DI Gerhard Kreuzer, www.liftoff.at
' *  ------------------------------------------------------------------------------------------------
' *  Version: MPL 1.1/GPL 2.0/LGPL 2.1
' *  
' *  The contents of this file are subject to the Mozilla Public License Version 
' *  1.1 (the "License"); you may not use this file except in compliance with 
' *  the License. You may obtain a copy of the License at 
' *  http://www.mozilla.org/MPL/
' *  
' *  Software distributed under the License is distributed on an "AS IS" basis,
' *  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
' *  for the specific language governing rights and limitations under the
' *  License.
' *  
' *  The Original Code is any part of this file that is not marked as a contribution.
' *  
' *  The Initial Developer of the Original Code is Gerhard Kreuzer
' *  Portions created by the Initial Developer are Copyright (C) 2007
' *  the Initial Developer. All Rights Reserved.
' *  
' *  Contributor(s): None.
' *  
' *  Alternatively, the contents of this file may be used under the terms of
' *  either the GNU General Public License Version 2 or later (the "GPL"), or
' *  the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
' *  in which case the provisions of the GPL or the LGPL are applicable instead
' *  of those above. If you wish to allow use of your version of this file only
' *  under the terms of either the GPL or the LGPL, and not to allow others to
' *  use your version of this file under the terms of the MPL, indicate your
' *  decision by deleting the provisions above and replace them with the notice
' *  and other provisions required by the GPL or the LGPL. If you do not delete
' *  the provisions above, a recipient may use your version of this file under
' *  the terms of any one of the MPL, the GPL or the LGPL.
' *--------------------------------------------------------------------------------------------------
' */
#End Region

Imports System.Reflection
Imports System.Threading
Imports System.Collections.Generic
Imports System.Text
Imports PostSharp.Laos

<Serializable()> _
Public NotInheritable Class CacheAspect
    Inherits OnMethodBoundaryAspect

#Region "Shared Variables"
    Private Shared myCache As New Dictionary(Of String, Object)
    'Lock, to get thread safe access to our counters
    Private Shared myStatisticLock As New ReaderWriterLock
    'Some counters for overall usage statistics
    Private Shared myCacheHits, myCacheFaults As Integer
#End Region

#Region "Helper"
    'IMPORTANT NOTE: 
    'This function is not certified for real live usage, its only a quick and dirty solution, satisfying the needs of this sample only!!
    Private Function MakeCacheTag(ByVal t As Type, ByVal mi As MethodInfo, ByVal argList As Object()) As String
        Dim sb As New StringBuilder
        sb.Append(t.AssemblyQualifiedName)
        sb.Append("@")
        sb.Append(mi.ToString)

        If argList IsNot Nothing Then
            For Each obj As Object In argList
                sb.Append("@")
                sb.Append(obj.ToString)
            Next
        End If
        Return sb.ToString
    End Function

    Private Sub IncrementCacheHits()
        myStatisticLock.AcquireWriterLock(1000)
        myCacheHits += 1
        myStatisticLock.ReleaseWriterLock()
    End Sub

    Private Sub IncrementCacheFaults()
        myStatisticLock.AcquireWriterLock(1000)
        myCacheFaults += 1
        myStatisticLock.ReleaseWriterLock()
    End Sub
#End Region

#Region "Overrides"
    'Validate at compile time: This aspect only works on non-constructing methods, without out parameters but with return value of any type
    'Logical issues can't be checked, for instance, somebody caches a method, which access a database ....
    Public Overrides Function CompileTimeValidate(ByVal method As System.Reflection.MethodBase) As Boolean
        If method.IsConstructor Then
            Throw New Exception("Caching of constructors is not allowed")
            Return False
        Else
            Dim mi As MethodInfo = DirectCast(method, MemberInfo)
            If mi.ReturnType Is Nothing Then
                Throw New Exception("Methods without return value are not cache-able")
                Return False
            Else
                For Each pi As ParameterInfo In mi.GetParameters
                    If pi.IsOut Then
                        Throw New Exception("Out-parameters are not cacheable")
                        Return False
                    End If
                Next
                'Here we go
                Return True
            End If
        End If
    End Function

    Public Overrides Sub OnEntry(ByVal eventArgs As MethodExecutionEventArgs)
        With eventArgs
            Dim retVal As Object
            Dim cacheTag As String = MakeCacheTag(.Instance.GetType, .Method, .GetArguments)
            Dim cacheHit As Boolean
            'We use a shared object from an instance method,  so we have to lock it during our operations, 
            'to be threadsafe.
            'Its in the nature of declararive programming, that our CacheAspect is often added at a very late phase of a project,
            'during performance tuning for instance, and may be used by more than one thread.
            SyncLock myCache
                cacheHit = myCache.TryGetValue(cacheTag, retVal)
            End SyncLock
            If cacheHit Then
                IncrementCacheHits()
                .ReturnValue = retVal
                .FlowBehavior = FlowBehavior.Return
            Else
                IncrementCacheFaults()
                .MethodExecutionTag = cacheTag
                MyBase.OnEntry(eventArgs)
            End If
        End With
    End Sub

    Public Overrides Sub OnSuccess(ByVal eventArgs As MethodExecutionEventArgs)
        With eventArgs
            'We use a shared object from an instance method,  so we have to lock it during our operations, 
            'to be threadsafe.
            'Its in the nature of declararive programming, that our CacheAspect is often added at a very late phase of a project,
            'during performance tuning for instance, and may be used by more than one thread.
            SyncLock myCache
                myCache.Add(.MethodExecutionTag, .ReturnValue)
            End SyncLock
        End With
        MyBase.OnSuccess(eventArgs)
    End Sub
#End Region

#Region "Shared Interface"
    Public Shared ReadOnly Property Hits() As Integer
        Get
            Dim actCount As Integer
            myStatisticLock.AcquireReaderLock(1000)
            actCount = myCacheHits
            myStatisticLock.ReleaseReaderLock()
            Return actCount
        End Get
    End Property

    Public Shared ReadOnly Property Faults() As Integer
        Get
            Dim actCount As Integer
            myStatisticLock.AcquireReaderLock(1000)
            actCount = myCacheFaults
            myStatisticLock.ReleaseReaderLock()
            Return actCount
        End Get
    End Property
#End Region

End Class
